//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using CommunityServer.Components;
using Sgml;

namespace CommunityServer.Reader.Components
{
	/// <summary>
	/// Summary description for Folder.
	/// </summary>
	public class AutoDiscoverer
	{


		#region Private Members



		#endregion

		#region Constructor(s)

		public AutoDiscoverer()
		{

		}

		#endregion

		#region Properties

		

		#endregion

		#region Static Methods


		public static string DiscoverFeedUrl(string targetUrl)
		{
			XmlDocument targetSourceXml = ParseSiteSource(targetUrl);

			// Using XPath, we try to locate the <link> tag that contains the RSS href in it.
			XmlNodeList linkTags = targetSourceXml.SelectNodes("/html/head/link[@type='application/rss+xml']");
	
			// if we managed to get something, continue.
			if (linkTags.Count > 0)
			{
				XmlNode hrefNode = linkTags.Item(0).Attributes.GetNamedItem("href");

				if (hrefNode == null)
				{
					return null;
				}
				string href = hrefNode.Value;

				if (!href.ToLower().StartsWith("http://") && !href.ToLower().StartsWith("https://"))
				{
					if (!targetUrl.EndsWith("/"))
					{
						targetUrl = targetUrl + "/";
					}

					if (href.StartsWith("/"))
					{
						href = href.Substring(1, href.Length - 1);
					}

					href = targetUrl + href;
				}

				return href;
			}
			else
			{
				// Unable to load a specific URL, and no autodiscovery link specified. Display an error.
				return null;
			}			
		}

		/// <summary>
		/// This method takes a given URL and pulls the source of the homepage. It then runs the source through
		/// an SGML reader in order to get it into proper XHTML. Once it is in proper XHTML it loads it into a XmlDocument
		/// object and returns it to the caller.
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
		private static XmlDocument ParseSiteSource(string url)
		{
			WebRequest wreq				= CSRequest.CreateRequest(url);
			Stream webResponseStream	= wreq.GetResponse().GetResponseStream();
			StreamReader reader			= new StreamReader(webResponseStream, Encoding.ASCII);
			SgmlReader sgmlReader		= new SgmlReader();
			XmlDocument xmlDocument		= new XmlDocument();


			string responseHtml = reader.ReadToEnd().ToLower();


			sgmlReader.DocType = "HTML";
			sgmlReader.InputStream = new StringReader(responseHtml);

			xmlDocument.Load(sgmlReader);

			reader.Close();
			webResponseStream.Close();	

			return xmlDocument;
		}


		#endregion


	}
}
